rm(list = ls())

wd <- ".../Replication/"
setwd(wd)


# Load/install packages --
if (!require("pacman")) install.packages("pacman")
pacman::p_load(
  foreign, 
  ggplot2, 
  estimatr,
  texreg,
  xtable,
  fastDummies,
  sandwich,
  dplyr,
  janitor, 
  gridExtra,
  gsheet,
  zoo,
  interflex,
  lubridate,
  tidyverse,
  stringi,
  readxl,
  ri2,
  modelsummary,
  ggpubr
)

options(scipen=999)

# Note: given the random component inherent to the randomization tests performed
# by ri(), you may observe small differences in the p-values of the randomization
# tests performed using that function.

# Figure 1 --------------------------------------------------------------------

# load census data
c <- read.csv("Data/census_nonwhites.csv")
b <- read.csv("Data/census_whites.csv")


c$slave <- ifelse(c$slave==1, "Enslaved", "Free\n ")
c <- c[!is.na(c$slave), ]
c$facet <- "Non-Whites"

c %>% group_by(slave) %>% 
  dplyr::summarize(sh_imprisoned_01 = mean(imprisoned>0))

by_slave <- c %>%
  group_by(slave, facet) %>% 
  dplyr::summarize(sh_imprisoned_01 = mean(imprisoned>0)) %>%
  ggplot(aes(x=slave, y=sh_imprisoned_01, fill = slave)) + 
  geom_col() +
  scale_fill_grey() +   
  theme_minimal() +
  theme(legend.position = "none") +
  ylab("Imprisoned") +
  facet_wrap(~facet) + 
  ylim(0,.115) +
  xlab("")

c <- c[!is.na(c$race) & c$race!="Indio" & c$race!="Mestizo", ]
c$race[c$race %in% c("Mulato", "Pardo")] <- "Mixed-Race"
c$race[c$race %in% c("Moreno", "Negro")] <- "Black"
c$race[c$race=="Non-white (unknown)"] <- "Non-White\n(unknown)"

by_race_enslaved <- c %>%
  group_by(race, slave) %>% 
  dplyr::summarize(sh_imprisoned_01 = mean(imprisoned>0)) %>%
  ggplot(aes(x=slave, y=sh_imprisoned_01, fill = slave)) + 
  geom_col() +
  scale_fill_grey() +  
  theme_minimal() +
  theme(legend.position = "none") +
  facet_wrap(~race) + 
  ylab("Imprisoned") +
  xlab("") +
  ylim(0,.115)


b$facet <- "Whites"
b$patricio <- ifelse(b$patria %in% c("patricio","patricia","patrico","patricio-España"), "High-Status", "Low-Status")

whites <- b %>%
  group_by(patricio , facet) %>% 
  dplyr::summarize(sh_imprisoned_01 = mean(detenciones>0)) %>% 
  ggplot(aes(x=patricio , y=sh_imprisoned_01)) + 
  geom_col(fill = "grey80") +
  theme_minimal() +
  theme(legend.position = "none") +
  ylab("Imprisoned") +
  facet_wrap(~facet) + 
  xlab(" ") +
  ylim(0,.115)

pdf("Output/Figure1.pdf",height=4, width=5)
ggarrange(ggarrange(whites, by_slave,
                    ncol=2, labels = c("A", "B"), 
                    widths = c(1, 1),
                    heights = c(1, 1),
                    align = "h",
                    font.label = list(size = 12)), 
          by_race_enslaved, 
          nrow=2, labels = c("", "C"), 
          widths = c(1, 1),
          heights = c(1, 1),
          font.label = list(size = 12))
dev.off()
